package com.gitee.elf.core.entity.trait

import com.gitee.elf.api.annotation.Id
import com.gitee.elf.core.entity.EntityInstance
import com.gitee.elf.core.entity.EntityStatus
import com.gitee.elf.core.entity.EntityTheme
import com.gitee.elf.core.entity.event.EntityEventManager.invokeScript
import com.gitee.elf.core.entity.event.EntityScheduledTaskEvent
import taboolib.common.platform.function.submitAsync

@Id("scheduled task")
class TraitScheduledTask(instance: EntityInstance) : AbstractTrait(instance) {

    val handlers = theme?.events?.filter { it.bindEvent == EntityScheduledTaskEvent }?.map { Handler(it) } ?: emptyList()

    val handlerTasks = handlers.map {
        submitAsync(period = it.period, delay = it.delay) {
            if (it.isActive) {
                if (instance.status == EntityStatus.ACTIVE) {
                    instance.invokeScript(it.handler)
                }
            } else {
                instance.invokeScript(it.handler)
            }
        }
    }

    class Handler(val handler: EntityTheme.EventHandler) {

        val delay = handler.config.getLong("delay", 0)

        val period = handler.config.getLong("period", 100)

        val isActive = handler.config.getBoolean("active", false)

    }

}